package com.sjf.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sjf.common.CustomException;
import com.sjf.reggie.entity.User;
import com.sjf.reggie.mapper.UserMapper;
import com.sjf.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author <huangtang>
 * @since 2022/4/27 0:28
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public  User  login ( HttpServletRequest request,String phone , String code ) {
        //获取Session中的code
        //String originCode = (String)request.getSession ().getAttribute ("code");
        //从Redis中获取验证码
        Object obj = redisTemplate.opsForValue ().get (phone);
        //对Code进行校验
        if(!obj.equals ( code )){
            throw new CustomException ("验证码错误！");
        }
        //根据手机号查询用户
        User user = getOne (new QueryWrapper<User> ().eq ("phone" , phone));
        if(user == null){
            //如果用户不存在，则创建用户
            user = new User ();
            user.setPhone ( phone );
            save (user);
        }
        request.getSession ().setAttribute ("user" , user.getId ());
        //用户登录成功，删除redis中缓存的验证码
        redisTemplate.delete (phone);
        return user;
    }
}
